$(function () {
    $("#codeurl").attr("src", URLA + '/code?date=' + Math.random());
})



function judge() {
    var username = document.getElementById("username").value;
    var password = document.getElementById("password").value;
    //这里需要判断，空格，输入字符串的长度 6-16，不能为中文，特殊字符;引入正则表达式
    var reg = /^[a-zA-Z]\w{5,15}$/;
    if (reg.test(username)) {
        document.getElementById("spanUsername").innerHTML = "当前用户名可用使用 ";
    } else {
        document.getElementById("spanUsername").innerHTML = "你输入的是火星文，地球人都不认识";
        document.getElementById("username").focus();
        return false;
    }
    if (reg.test(password)) {
        $("#spanPassword").html("密码格式正确");
    } else {
        $("#spanPassword").html("你输入的密码不符合规范");
        $("#password").focus();
        return false;
    }

    return true;

}


function getUserDataById() {
    // sessionStorage.getItem()
    let id = localStorage.getItem("userId");
    $.ajax({
        url: '/findUserById',
        data: {userId: id},
        type: 'get',
        dataType: 'json',
        success: function (data) {
            setUserData(data[0]);
        }
    })
    localStorage.setItem("userId", null);
}

function setUserData(data) {
    $("#id").val(data.id);
    $("#username").val(data.username);
    $("#password").val(data.password);
}

function saveData() {
    let data = {id: $("#id").val(), username: $("#username").val(), password: $("#password").val()};
    if (judge()) {
        $.ajax({
            url: '/userAdd',
            data: data,
            type: 'post',
            dataType: 'json',
            success: function (data) {
                alert(data[0].result);
                $('#backright').load('/back/userSelect.jsp');
            }
        })
    }
}

function changeImg(e) {
    e.src = URLA + '/code?date=' + Math.random();
}

function toRegisterJsp() {
    window.open("/back/userAdd.jsp");
    // document.getElementById("username").value="";//清空
    // window.location.href="/back/userAdd.jsp";
}

function login() {
    if (judge()) {

        $.ajax({
            url: '/login',
            type: 'get',
            dataType: 'json',
            // xhrFields: {
            //     withCredentials: true //允许跨域带Cookie
            // },
            success: function (data) {
                if (data[0].code == 200) {
                    var date = new Date();
                    date.setTime(date.getTime() + 30 * 60 * 1000);
                    $.cookie("token", data[0].result, {
                        expires: date
                    });

                    window.open("/back/home.jsp");
                } else {
                    alert(data[0].result);
                    $("#username").focus();
                }
            }
        })
    }
}
